<!-- 公用树组件 -->
<template>
  <div class="gyk-tree-box">
    <!-- 搜索输入框 -->
    <el-input style="margin-bottom: 16px;" v-model="filterText" placeholder="输入搜索条件" />

    <el-scrollbar>
      <!-- 树形组件 -->
      <el-tree empty-text="没有数据" ref="commonTreeRef" :filter-node-method="filterNode" @node-click="treeNodeClick"
        :data="treeData" :props="treeProps" node-key="id" :expand-on-click-node="false">
        <template #default="{ node, data }">
          <span class="gyk-customer-node">
            <img class="gyk-customer-node__icon" src="~@/assets/images/tree_folder.png" />
            <span>{{ data[treeProps.label] }}</span>
          </span>
        </template>
      </el-tree>
    </el-scrollbar>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, reactive } from 'vue'
import { useCssVar } from '@vueuse/core'

const commonTreeRef = ref()
// 搜索文本
const filterText = ref('')

// 过滤节点
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.label.includes(value)
}

watch(filterText, (val) => {
  commonTreeRef.value!.filter(val)
})

onMounted(() => {
})

interface Tree {
  id: number
  label: string
  children?: Tree[]
}

interface TreeProps {
  label: string
  value: string
  children: string
}

const defProps = withDefaults(defineProps<{
  treeData: Tree[],
  treeProps: TreeProps,
  width: string,
}>(), {
  treeData: () => [],
  treeProps: () => {
    return {
      label: 'label',
      value: 'id',
      children: 'children'
    }
  },
  width: '280'
})

const emit = defineEmits<{
  (e: "onTreeNodeClick", obj: any, node: any, treeNode: any, event: any): void
}>()

const treeNodeClick = (obj, node, treeNode, event) => {
  const elements = document.querySelectorAll(".el-tree-node__content")
  // 遍历元素，并移除 class
  for (var element of elements) {
    element.classList.remove("is-active");
  }
  const activeEl = event.target.closest('.el-tree-node__content')
  activeEl.classList.add("is-active")
  emit("onTreeNodeClick", obj, node, treeNode, event)
}
</script>

<style lang="scss" scoped>
@include b(tree-box) {
  @include bfc;
  display: flex;
  flex-direction: column;
  width: v-bind(width);

  :deep(.el-tree-node__content) {
    @include useTheme {
      height: 40px !important;
      background-color: getVar('treeNodeBgColor') !important;
    }

    &.is-active {
      @include useTheme {
        background-color: getVar('treeNodeHoverBgColor');
      }
    }

    &:hover {
      @include useTheme {
        background-color: getVar('treeNodeHoverBgColor') !important;
      }
    }

    @include b(customer-node) {
      display: flex;
      align-items: center;

      @include e(icon) {
        width: 14px;
        height: 14px;
        margin-right: 8px;
      }
    }
  }
}</style>